import locale
from datetime import datetime

from docx import Document
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Pt, Inches

locale.setlocale(locale.LC_CTYPE, 'chinese')

cols = ['no', 'zw', 'diya', 'qzName', 'amount', 'qzNo', 'remark']
default_border = {
    'top': {"sz": 12, "val": "single", "color": "#000000", "space": "0"},
    'bottom': {"sz": 12, "val": "single", "color": "#000000", "space": "0"},
    'left': {"sz": 12, "val": "single", "color": "#000000", "space": "0"},
    'right': {"sz": 12, "val": "single", "color": "#000000", "space": "0"},
}


def set_font(run, font_size=12):
    run.font.name = u'宋体'
    run.font.size = Pt(font_size)
    run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')


def set_cell_border(cell, border=None):
    """
    Set cell`s border
    Usage:
    set_cell_border(
        cell,
        top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
        bottom={"sz": 12, "color": "#00FF00", "val": "single"},
        left={"sz": 24, "val": "dashed", "shadow": "true"},
        right={"sz": 12, "val": "dashed"},
    )
    """
    if border is None:
        border = default_border
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()

    # check for tag existnace, if none found, then create one
    tcBorders = tcPr.first_child_found_in("w:tcBorders")
    if tcBorders is None:
        tcBorders = OxmlElement('w:tcBorders')
        tcPr.append(tcBorders)

    # list over all available tags
    for edge in ('left', 'top', 'right', 'bottom', 'insideH', 'insideV'):
        edge_data = border.get(edge)
        if edge_data:
            tag = 'w:{}'.format(edge)

            # check for tag existnace, if none found, then create one
            element = tcBorders.find(qn(tag))
            if element is None:
                element = OxmlElement(tag)
                tcBorders.append(element)

            # looks like order of attributes is important
            for key in ["sz", "val", "color", "space", "shadow"]:
                if key in edge_data:
                    element.set(qn('w:{}'.format(key)), str(edge_data[key]))


def generate_table(count_list, items, file_path):
    document = Document()

    table = document.add_table(cols=7, rows=0)

    table.add_row()
    col_width_dic = [
        753,
        1350,
        1440,
        1650,
        495,
        2250,
        700,
    ]
    for col_num in range(7):
        table.cell(0, col_num).width = Inches(col_width_dic[col_num])

    table.cell(0, 0).merge(table.cell(0, 1))

    run = table.cell(0, 0).paragraphs[0].add_run(u'附件2：')

    set_font(run, 14)
    run.font.bold = True

    table.add_row()
    table.cell(1, 0).merge(table.cell(1, 6))
    run = table.cell(1, 0).paragraphs[0].add_run(u'中国邮政储蓄银行押品权证暂存库入库凭证')
    table.cell(1, 0).paragraphs[0].paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    set_font(run, 14)
    run.font.bold = True

    # 3
    for inx, count in enumerate(count_list):
        row = table.add_row()
        table.cell(2 + inx, 3).merge(table.cell(2 + inx, 4))
        if inx == 0:
            run = table.cell(2 + inx, 4).paragraphs[0].add_run(u'编号:')
            table.cell(2 + inx, 4).paragraphs[0].paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
            set_font(run)
        run = table.cell(2 + inx, 5).paragraphs[0].add_run(count)
        set_font(run)

    row = table.add_row()
    current_inx = table.rows.__len__() - 1
    table.cell(current_inx, 0).merge(table.cell(current_inx, 6))
    run = table.cell(current_inx, 0).paragraphs[0].add_run(u'盐城市（分/支）行会计与营运部：')
    set_font(run)

    row = table.add_row()
    current_inx = table.rows.__len__() - 1
    table.cell(current_inx, 0).merge(table.cell(current_inx, 6))
    run = table.cell(current_inx, 0).paragraphs[0].add_run(u'\t下列权利证书作为债务人在我行借款的抵（质）押凭证，请予以办理入库手续。')
    set_font(run)

    # 以下所有单元格设置边框

    row = table.add_row()
    current_inx += 1

    start_line = current_inx

    table.cell(current_inx, 0).merge(table.cell(current_inx, 6))
    run = table.cell(current_inx, 0).paragraphs[0].add_run(u'申请入库封包清单')
    table.cell(current_inx, 0).paragraphs[0].paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    set_font(run, 10.5)
    run.font.bold = True

    current_inx += 1
    row = table.add_row()
    for inx, text in enumerate(['序号', '债务人名称', '抵押人/出质人名称', '押品权证名称', '数量', '权证编码', '备注']):
        run = table.cell(current_inx, inx).paragraphs[0].add_run(text)
        table.cell(current_inx, inx).paragraphs[0].paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        set_font(run, 10.5)
        run.font.bold = True

    for item_inx, item in enumerate(items):
        current_inx += 1
        row = table.add_row()
        for colInx, col in enumerate(cols):
            if colInx == 0:
                run = table.cell(current_inx, colInx).paragraphs[0].add_run(str(item_inx + 1))
            else:
                run = table.cell(current_inx, colInx).paragraphs[0].add_run(item.get(col))
            table.cell(current_inx, colInx).paragraphs[0].paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
            set_font(run, 10.5)
            run.font.bold = True

    # 准备四行
    current_inx += 1
    table.add_row()

    run = table.cell(current_inx, 0).paragraphs[0].add_run(u'押品移交相关人员意见')
    table.cell(current_inx, 0).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
    set_font(run, 10.5)
    run.font.bold = True

    # 合并之后的单元格
    table.cell(current_inx, 1).merge(table.cell(current_inx, 6))

    # 在这个单元格中插入表格
    cell_table = table.cell(current_inx, 1).add_table(rows=4, cols=1)

    run = cell_table.cell(0, 0).paragraphs[0].add_run(u'移交人员：\n')
    set_font(run, 10.5)

    run = cell_table.cell(1, 0).paragraphs[0].add_run(u'日期： ' + datetime.now().strftime('%Y年%m月%d日'))
    cell_table.cell(1, 0).paragraphs[0].paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
    set_font(run, 10.5)

    run = cell_table.cell(2, 0).paragraphs[0].add_run(u'\n接收人员：\n')
    set_font(run, 10.5)

    run = cell_table.cell(3, 0).paragraphs[0].add_run(u'日期： ' + datetime.now().strftime('%Y年%m月%d日'))
    cell_table.cell(3, 0).paragraphs[0].paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
    set_font(run, 10.5)

    # 为cell_table 添加边框
    for row_index in range(cell_table.rows.__len__()):
        if row_index in [0, 2, 3]:
            continue
        for col_inx in range(cell_table.columns.__len__()):
            cell = cell_table.cell(row_index, col_inx)
            set_cell_border(cell, border={'bottom': {"sz": 12, "val": "single", "color": "#000000", "space": "0"}})

    for row_index in range(table.rows.__len__() - start_line):
        for col_inx in range(table.columns.__len__()):
            cell = table.cell(start_line + row_index, col_inx)
            set_cell_border(cell)

    document.save(file_path)
